/**
 * 统一请求封装
 */

interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: Record<string, string>;
  showLoading?: boolean;
}

interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}

class Request {
  private baseURL = '';
  private timeout = 10000;

  constructor() {
    // 可以在这里设置基础URL
  }

  /**
   * 统一请求方法
   */
  async request<T = any>(options: RequestOptions): Promise<ApiResponse<T>> {
    const { url, method = 'GET', data, header = {}, showLoading = true } = options;

    // 显示加载提示
    if (showLoading) {
      uni.showLoading({
        title: '加载中...'
      });
    }

    try {
      const response = await uni.request({
        url: this.baseURL + url,
        method,
        data,
        header: {
          'Content-Type': 'application/json',
          ...header
        },
        timeout: this.timeout
      });

      if (showLoading) {
        uni.hideLoading();
      }

      const result = response.data as ApiResponse<T>;
      
      // 统一错误处理
      if (result.code !== 200) {
        uni.showToast({
          title: result.message || '请求失败',
          icon: 'none'
        });
        throw new Error(result.message);
      }

      return result;
    } catch (error) {
      if (showLoading) {
        uni.hideLoading();
      }
      
      uni.showToast({
        title: '网络请求失败',
        icon: 'none'
      });
      
      throw error;
    }
  }

  get<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>({ url, method: 'GET', data });
  }

  post<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>({ url, method: 'POST', data });
  }

  put<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>({ url, method: 'PUT', data });
  }

  delete<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>({ url, method: 'DELETE', data });
  }
}

export const request = new Request();
export type { RequestOptions, ApiResponse };